package com.hash;

import java.util.HashMap;
import java.util.Map;

/**
 * 子数组和等于K
 */
public class SubArraySum {

    /**
     * [1, 1, 1]
     * [1, 2, 3]
     * @param args
     */
    public static void main(String[] args) {
        int[] nums = {1, 1, 1};
        int k = 2;

        int ret = subarraySum(nums, k);
        System.out.println(ret);
    }

    public static int subarraySum(int[] nums, int k) {
        if (nums == null || nums.length == 0) return 0;

        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 1; i < nums.length; i++) {
            nums[i] += nums[i - 1];
        }
        int ans = 0;
        int tmp = 0;
        map.put(0, 1);
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i] - k)) {
                ans += map.get(nums[i] - k);
            }
            tmp = map.containsKey(nums[i]) ? map.get(nums[i]) + 1 : 1;
            map.put(nums[i], tmp);
        }
        return ans;
    }
}
